package com.example.fmgidsprototype.webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;

public class n_cst_web_service_interface {
	private static Context inv_context;
	private ProgressDialog iw_progress;
	private I_CallBack inv_call_back;
	private static final String WEBSERVICE_LOCATION = "http://192.168.0.142:8080/FM_Brussel_json/webresources/";
	//private static final String WEBSERVICE_LOCATION = "http://vps767.directvps.nl:8080/FM_Brussel_json/webresources/";
	
	
	public n_cst_web_service_interface(Context anv_context)
	{
		inv_context = anv_context;
	}
	
	private boolean of_check_connectivity()
	{
		ConnectivityManager connManager = (ConnectivityManager) inv_context.getSystemService(inv_context.CONNECTIVITY_SERVICE);
		NetworkInfo lnv_mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo lnv_wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		if (lnv_wifi.isConnected() || lnv_mobile.isConnected()) {
			return true;
		}
		else
		{
			Toast.makeText(inv_context.getApplicationContext(), "There is no WIFI nor 3G network available!", Toast.LENGTH_LONG).show();
			
			return false;
		}
	}
	
	private void of_show_progress(Boolean ab_show, String as_title, String as_message)
	{
		if (ab_show)
		{
			iw_progress = ProgressDialog.show(inv_context, as_title, as_message);	
		}
		else
		{
			if (iw_progress != null)
			{
				iw_progress.dismiss();	
			}			
		}
	}
	
	public void of_get_categories(Date adt_modified_date, I_CallBack anv_call_back)
	{
		if (of_check_connectivity())
		{
			of_show_progress(true, "Retrieving venues", "Loading...");
			
			inv_call_back = anv_call_back;
			
			n_cst_async_categories_json lnv_async_categories_json = new n_cst_async_categories_json();
			lnv_async_categories_json.execute(adt_modified_date);
			
			of_show_progress(false, "Retrieving venues", "Loading...");
		}
	}
	
	public void of_get_reviews(Date adt_modified_date, I_CallBack anv_call_back)
	{
		if (of_check_connectivity())
		{
			of_show_progress(true, "Retrieving reviews", "Loading...");
			
			inv_call_back = anv_call_back;
			
			n_cst_async_reviews_json lnv_async_reviews_json = new n_cst_async_reviews_json();
			lnv_async_reviews_json.execute(adt_modified_date);
			
			of_show_progress(false, "Retrieving venues", "Loading...");
		}
	}
	
	public void of_save_rating(Integer ai_json_id, Float ad_rating, String as_user_name)
	{	
		if (of_check_connectivity())
		{
			String ls_Args[] = {ai_json_id.toString(), ad_rating.toString(), as_user_name};
			of_show_progress(true, "Saving ratings", "Saving...");
			
			n_cst_async_rating lnv_async_rating = new n_cst_async_rating();
			lnv_async_rating.execute(ls_Args);
			
			of_show_progress(false, "Saving ratings", "Saving...");
		}
	}
	
	private class n_cst_async_rating extends AsyncTask<String, Integer, String>
	{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Integer li_json_id = Integer.valueOf(params[0]);
			Float ld_rating = Float.valueOf(params[1]);
			String ls_user_name = params[2];
			
			final String ls_tag = "Your Logcat tag: ";
	
			String ls_Url = String.format(WEBSERVICE_LOCATION + "get_categories_venues/%d/%f/%s", li_json_id, ld_rating, ls_user_name);

			of_execute_url(ls_Url);
	        
	        return "ok";
		}		
	}
	
	public void of_save_review(Integer ai_json_id, String as_review, String as_user_name)
	{
		if (of_check_connectivity())
		{
			String ls_Args[] = {ai_json_id.toString(), as_review, as_user_name};
			of_show_progress(true, "Saving review", "Saving...");
			
			n_cst_async_review lnv_async_review = new n_cst_async_review();
			lnv_async_review.execute(ls_Args);
			
			of_show_progress(false, "Saving review", "Saving...");
		}
	}
	
	private class n_cst_async_review extends AsyncTask<String, Integer, String>
	{
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Integer li_json_id = Integer.valueOf(params[0]);
			String ls_review = params[1];
			String ls_user_name = params[2];
		
			final String ls_tag = "Your Logcat tag: ";
			
			String ls_Url = String.format(WEBSERVICE_LOCATION + "get_reviews/%d/%s/%s", li_json_id, ls_review, ls_user_name);

			of_execute_url(ls_Url);
	        
	        return "ok";
		}		
	}
	
	private class n_cst_async_categories_json extends AsyncTask<Date, Integer, String>
	{
		@Override
		protected void onPreExecute() {};
		
		@Override
		protected String doInBackground(Date... params) {
			// TODO Auto-generated method stub
			String ls_date="";
			String ls_return = "";
			/* original json Werner 
			String ls_json = "{'modified_date':'2013-05-10','categories':[{'id':1,'name':'Cultuur','description':'culturele venues in Brussel','icon_name':'cultuur.png','modified_date':'2013-05-10'," +
					"'venues':[{'id':1,'json_id':100,'name':'Afgietselwerkplaats','description':'Magische blast from the past','address_nl':'Jubelpark 10, 1000 Brussel','address_fr':'Jubelpark 10, 1000 Brussel','thumb_name':'afgietselwerkplaats.jpg','image_url':'afgietselwerkplaats.jpg','url':'http://www.kmkg-mrah.be/nl/afgietselwerkplaats-0','email':'','phone':'tel:32486789698','audio_path':'afgietselwerkplaats.mp3','longitude':'4.391570','latitude':'50.838888','distance_from_point_zero':'650','rating':'3.0000','votes':2,'modified_date':'2013-05-10'}," +
					"{'id':2,'json_id':101,'name':'Box Galerie','description':'Kwaliteitsgalerie gespecialiseerd in fotografie','address_nl':'Maliestraat 88, 1050 Elsene','address_fr':'Maliestraat 88, 1050 Elsene','thumb_name':'box_galerie.jpg','image_url':'box_galerie.jpg','url':'http://www.boxgalerie.be','email':'','phone':'tel:32486526824','audio_path':'','longitude':'4.358804','latitude':'50.821608','distance_from_point_zero':'320','rating':'0','votes':0,'modified_date':'2013-05-10'}," +
					"{'id':3,'json_id':102,'name':'De Centrale','description':'Hedendaagse kunst in het centrum van de stad','address_nl':'Sint-Katelijneplein 44, 1000 Brussel','address_fr':'Sint-Katelijneplein 44, 1000 Brussel','thumb_name':'de_centrale.jpg','image_url':'de_centrale.jpg','url':'','email':'','phone':'tel:32476255225','audio_path':'','longitude':'4.348462','latitude':'50.850201','distance_from_point_zero':'1020','rating':'0','votes':0,'modified_date':'2013-05-10'}]}," +
					"{'id':2,'name':'Bars','description':'van bruine kroegen tot trendy cocktailbars','icon_name':'cafe.png','modified_date':'2013-05-10','venues':" +
					"[{'id':4,'json_id':103,'name':'De Loge','description':'Hedendaagse kunst in vrijmetselaarstempel','address_nl':'Kluisstraat 86, 1050 Elsene','address_fr':'Kluisstraat 86, 1050 Elsene','thumb_name':'de_loge.jpg','image_url':'de_loge.jpg','url':'http://www.la-loge.be/la-loge','email':'','phone':'tel:32495824673','audio_path':'','longitude':'4.365563','latitude':'50.828805','distance_from_point_zero':'170','rating':'1.0000','votes':1,'modified_date':'2013-05-10'}," +
					"{'id':5,'json_id':104,'name':'De Loketten','description':'Expos in monumentale lokettenhal van het Vlaams Parlement','address_nl':'Ijzerenkruisstraat 99, 1000 Brussel','address_fr':'Ijzerenkruisstraat 99, 1000 Brussel','thumb_name':'de_loketten.jpg','image_url':'de_loketten.jpg','url':'http://www.vlaamsparlement.be/vp/contact/bezoeken/deloketten.html','email':'','phone':'tel:32498242324','audio_path':'','longitude':'4.367623','latitude':'50.848806','distance_from_point_zero':'520','rating':'0','votes':0,'modified_date':'2013-05-10'}]" +
					"}," +
					"{'id':3,'name':'NightLife','description':'Feesten in Brussel','icon_name':'nightlife.png','modified_date':'2013-05-10','venues':" +
					"[{'id':6,'json_id':105,'name':'London Calling','description':'Muziekbar met partykelder op het herboren Londenplein','address_nl':'Dublinstraat 46, 1050 Elsene','address_fr':'','thumb_name':'london_calling.jpg','image_url':'london_calling.jpg','url':'https://www.facebook.com/Londoncallingdublin','email':'','phone':'tel:32476406804','audio_path':'','longitude':'50.83821','latitude':'4.367792','distance_from_point_zero':'225','rating':'4.5','votes':1,'modified_date':'2013-05-10'}]" +
					"}" +
					"]}";*/
			String ls_json = "{'modified_date':'2013-05-10','categories':[{'id':1,'name':'Cultuur','description':'culturele venues in Brussel','icon_name':'cultuur.png','modified_date':'2013-05-10'," +
					"'venues':[{'id':1,'json_id':100,'name':'Afgietselwerkplaats','description':'Magische blast from the past','address_nl':'Jubelpark 10, 1000 Brussel','address_fr':'Jubelpark 10, 1000 Brussel','thumb_name':'afgietselwerkplaats.jpg','image_url':'afgietselwerkplaats.jpg','url':'http://www.kmkg-mrah.be/nl/afgietselwerkplaats-0','email':'','phone':'tel:32486789698','audio_path':'afgietselwerkplaats.mp3','longitude':'4.391545','latitude':'50.838928','distance_from_point_zero':'650','rating':'3.0000','votes':2,'modified_date':'2013-05-10'}," +
					"{'id':2,'json_id':101,'name':'Box Galerie','description':'Kwaliteitsgalerie gespecialiseerd in fotografie','address_nl':'Maliestraat 88, 1050 Elsene','address_fr':'Maliestraat 88, 1050 Elsene','thumb_name':'box_galerie.jpg','image_url':'box_galerie.jpg','url':'http://www.boxgalerie.be','email':'','phone':'tel:32486526824','audio_path':'','longitude':'4.358779','latitude':'50.821675','distance_from_point_zero':'320','rating':'0','votes':0,'modified_date':'2013-05-10'}," +
					"{'id':3,'json_id':102,'name':'De Centrale','description':'Hedendaagse kunst in het centrum van de stad','address_nl':'Sint-Katelijneplein 44, 1000 Brussel','address_fr':'Sint-Katelijneplein 44, 1000 Brussel','thumb_name':'de_centrale.jpg','image_url':'de_centrale.jpg','url':'','email':'','phone':'tel:32476255225','audio_path':'de_centrale.mp3','longitude':'4.348866','latitude':'50.851028','distance_from_point_zero':'1020','rating':'0','votes':0,'modified_date':'2013-05-10'}]}," +
					"{'id':2,'name':'Bars','description':'van bruine kroegen tot trendy cocktailbars','icon_name':'cafe.png','modified_date':'2013-05-10','venues':" +
					"[{'id':4,'json_id':103,'name':'De Loge','description':'Hedendaagse kunst in vrijmetselaarstempel','address_nl':'Kluisstraat 86, 1050 Elsene','address_fr':'Kluisstraat 86, 1050 Elsene','thumb_name':'de_loge.jpg','image_url':'de_loge.jpg','url':'http://www.la-loge.be/la-loge','email':'','phone':'tel:32495824673','audio_path':'','longitude':'4.365563','latitude':'50.828805','distance_from_point_zero':'170','rating':'1.0000','votes':1,'modified_date':'2013-05-10'}," +
					"{'id':5,'json_id':104,'name':'De Loketten','description':'Expos in monumentale lokettenhal van het Vlaams Parlement','address_nl':'Ijzerenkruisstraat 99, 1000 Brussel','address_fr':'Ijzerenkruisstraat 99, 1000 Brussel','thumb_name':'de_loketten.jpg','image_url':'de_loketten.jpg','url':'http://www.vlaamsparlement.be/vp/contact/bezoeken/deloketten.html','email':'','phone':'tel:32498242324','audio_path':'','longitude':'4.367623','latitude':'50.848806','distance_from_point_zero':'520','rating':'0','votes':0,'modified_date':'2013-05-10'}]" +
					"}," +
					"{'id':3,'name':'NightLife','description':'Feesten in Brussel','icon_name':'nightlife.png','modified_date':'2013-05-10','venues':" +
					"[{'id':6,'json_id':105,'name':'London Calling','description':'Muziekbar met partykelder op het herboren Londenplein','address_nl':'Dublinstraat 46, 1050 Elsene','address_fr':'','thumb_name':'london_calling.jpg','image_url':'london_calling.jpg','url':'https://www.facebook.com/Londoncallingdublin','email':'','phone':'tel:32476406804','audio_path':'','longitude':'4.367792','latitude':'50.83821','distance_from_point_zero':'225','rating':'4.5','votes':1,'modified_date':'2013-05-10'}]" +
					"}," +
					"{'id':4,'name':'Kids','description':'Waar naartoe met de kinderen','icon_name':'kids.png','modified_date':'2013-05-10','venues':" +
					"[{'id':99,'json_id':198,'name':'Baboes','description':'Een oase in de stad voor kinderen tot 4 jaar','address_nl':'Vlaamsesteenweg 159, 1000 Brussel','address_fr':'','thumb_name':'baboes.jpg','image_url':'baboes.jpg','url':'http://www.baboes.be','email':'','phone':'tel:3222190915','audio_path':'','longitude':'4.343652','latitude':'50.85306','distance_from_point_zero':'400','rating':'4.5','votes':1,'modified_date':'2013-05-10'}]" +
					"}," +
					"{'id':6,'name':'Escapism','description':'Even bezinnen','icon_name':'escapism.png','modified_date':'2013-05-10','venues':" +
					"[{'id':20,'json_id':119,'name':'Begraafplaats van Brussel','description':'Monumentale tombes op grootste kerkhof van Brussel','address_nl':'Jules Bordetlaan, 1140 Evere','address_fr':'','thumb_name':'begraafplaats_van_brussel.jpg','image_url':'begraafplaats_van_brussel.jpg','url':'','email':'','phone':'','audio_path':'','longitude':'4.417356','latitude':'50.872224','distance_from_point_zero':'200','rating':'5','votes':1,'modified_date':'2013-05-10'}]" +
					"}," +
					"{'id':7,'name':'Eten','description':'Buikje vullen in Brussel','icon_name':'eten.png','modified_date':'2013-05-10','venues':" +
					"[{'id':82,'json_id':181,'name':'Au Fond','description':'Eigenwijs klassiek en sympathiek','address_nl':'Antoine Dansaertstraat 78, 1000 Brussel','address_fr':'','thumb_name':'au_fond.jpg','image_url':'au_fond.jpg','url':'http://www.aufond.be','email':'','phone':'tel:3225032035','audio_path':'','longitude':'4.345604','latitude':'50.850933','distance_from_point_zero':'230','rating':'3.5','votes':1,'modified_date':'2013-05-10'}]" +
					"}" +
					"]}";
			
						
			
			SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy");

			Calendar cal = Calendar.getInstance();
			cal.setTime(params[0]);
			cal.add(Calendar.DAY_OF_MONTH, -15);
			
			ls_date = sdf.format(cal.getTime());
			ls_date = "May, 2 2010";
			
			ls_date = ls_date.replace(" ", "%20");
			
			//String ls_Url = "http://localhost:8080/FM_Brussel_json/webresources/db_json/January 2, 2010";
			String ls_Url = String.format(WEBSERVICE_LOCATION + "get_categories_venues/%s", ls_date);

			ls_return = of_execute_url(ls_Url);
			
			if (ls_return == "")
			{
				ls_return = ls_json;
			}
			
			return ls_return;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			n_cst_categories lnv_categories = new n_cst_categories();
			
			if (result != "")
			{
				lnv_categories = new Gson().fromJson(result, n_cst_categories.class);
			}
			else
			{
				lnv_categories = null;
			}
			
			if (inv_call_back != null)
			{
				inv_call_back.of_call_back(lnv_categories);
			}
		}
	}
	
	private class n_cst_async_reviews_json extends AsyncTask<Date, Integer, String>
	{
		@Override
		protected void onPreExecute() {};
		
		@Override
		protected String doInBackground(Date... params) {
			// TODO Auto-generated method stub
			String ls_date="";
			String ls_return = "";
			String ls_json = "{'reviews':[{'json_id':100,'review':'test','user_name':'Kurt','creation_date':'2013-05-16'},{'json_id':100,'review':'test2','user_name':'Kurt','creation_date':'2013-05-16'}]}";
			
			SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy");

			Calendar cal = Calendar.getInstance();
			cal.setTime(params[0]);
			cal.add(Calendar.DAY_OF_MONTH, -15);
			
			ls_date = sdf.format(cal.getTime());
			ls_date = "May, 2 2010";
			
			ls_date = ls_date.replace(" ", "%20");

			String ls_Url = String.format(WEBSERVICE_LOCATION + "get_reviews/%s", ls_date);
 
			ls_return = of_execute_url(ls_Url);
			
			if (ls_return == "")
			{
				ls_return = ls_json;
			}			 
	        
			return ls_return;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			n_cst_reviews lnv_reviews = new n_cst_reviews();
			
			if (result != "")
			{
				lnv_reviews = new Gson().fromJson(result, n_cst_reviews.class);
			}
			else
			{
				lnv_reviews = null;
			}
			
			if (inv_call_back != null)
			{
				inv_call_back.of_call_back(lnv_reviews);
			}
		}
	}
	

	
	private static String of_execute_url(String as_url)
	{
		String ls_return="";
		final String ls_tag = "Your Logcat tag: ";
		
		HttpParams httpParams = new BasicHttpParams();
	    HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
	    HttpConnectionParams.setSoTimeout(httpParams, 2000);
	    
		HttpClient httpclient = new DefaultHttpClient(httpParams); //AndroidHttpClient.newInstance("Android");
		
		try
		{
			HttpGet request = new HttpGet(as_url);		
            
	        try {   
	        	HttpResponse lnv_response = httpclient.execute(request);
	        	//ls_return = httpclient.execute(request, handler);
	        	StatusLine lnv_status = lnv_response.getStatusLine();
	        	
	        	int HTTP_STATUS_OK = 200;
				if (lnv_status.getStatusCode() == HTTP_STATUS_OK){
					HttpEntity entity = lnv_response.getEntity();
					InputStream lnv_input_stream = entity.getContent();

					BufferedReader reader = new BufferedReader(new InputStreamReader(lnv_input_stream));
				    StringBuilder lnv_string_builder = new StringBuilder();

				    String ls_line = null;
				    try {
				        while ((ls_line = reader.readLine()) != null) {
				        	lnv_string_builder.append(ls_line);
				        }
				        
				        ls_return = lnv_string_builder.toString();
				    } catch (IOException e) {
				        e.printStackTrace();
				    } finally {
				        try {
				        	lnv_input_stream.close();
				        } catch (IOException e) {
				            e.printStackTrace();
				        }
				    }					    	
	        	}
	        } catch (ClientProtocolException e) {   
	            e.printStackTrace();   
	        } catch (IOException e) {   
	            e.printStackTrace();   
	        }
		}
		catch (Exception ex)
		{
			if (ex.getMessage() == null)
			{
				Log.i(ls_tag, "Problems!!");	
			}
			else
			{
				Log.i(ls_tag, ex.getMessage());	
			}	
		}
		
        httpclient.getConnectionManager().shutdown();   
        httpclient = null;
		
        Log.i(ls_tag, ls_return);  
        
		return ls_return;
	}
}
